package com.ld.security.shop.im.modules.gro.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ld.security.common.core.base.po.PagePo;
import com.ld.security.common.core.base.vo.PageVo;
import com.ld.security.shop.im.modules.gro.constant.GroMsgUserConstant;
import com.ld.security.shop.im.modules.gro.entity.GroMsg;
import com.ld.security.shop.im.modules.gro.mapping.IGroMsgMapping;
import com.ld.security.shop.im.modules.gro.po.MsgUserPo;
import com.ld.security.shop.im.modules.gro.po.MsgUserThemePo;
import com.ld.security.shop.im.modules.gro.service.IGroMsgService;
import com.ld.security.shop.im.modules.gro.service.IGroMsgUserService;
import com.ld.security.shop.im.modules.gro.entity.GroMsgUser;
import com.ld.security.common.mybatis.base.service.*;
import com.ld.security.shop.im.modules.gro.vo.MsgUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
class GroMsgUserServiceImpl extends ISuperServiceImpl<GroMsgUser> implements
        IGroMsgUserService {

    @Autowired
    ProxyService proxyService;

    @Autowired
    IGroMsgService iGroMsgService;
    @Autowired
    IGroMsgMapping iGroMsgMapping;

    /**
     * 用户消息初始化
     * @param po
     */
    private void userMsgInit(MsgUserPo po ){

        DateTime y = DateUtil.date();
        DateTime x = DateUtil.offsetDay(y,-30);

        MsgUserThemePo q =  new MsgUserThemePo();
        q.setStartTime(x.toJdkDate());
        q.setEndTime(y.toJdkDate());
        q.setUserId(po.getUserId());
        List<GroMsg> list =   iGroMsgMapping.findByUserMsg(q);
        for (GroMsg groMsg : list) {
            GroMsgUser e =  this.newInstance();
            e.setMsgId(groMsg.getId());
            e.setUserId(po.getUserId());
            e.setMsgStatus(GroMsgUserConstant.msgStatus.unread);
            this.save(e);
        }
    }


    @Override
    public PageVo<MsgUserVo> findByUserId(PagePo<MsgUserPo> po) {

        userMsgInit(po.getQuery());

        PageVo<GroMsgUser> page =  this.page(po);
        List<MsgUserVo> list =  page.getList().stream().map(val -> {
            MsgUserVo vo =    new MsgUserVo();
            vo.setGroMsgUser(val);
            return vo;
        }).collect(Collectors.toList());
        proxyService.initMapping(MsgUserVo.class,list);
        PageVo page2 =  new PageVo<>();
        page2.setTotal(page.getTotal());
        page2.setList(list);
        return page2;
    }



}
